const Router = require('koa-router')
// 引入guidance数据库模块
const Guidances = require('../../models/Guidance')
// 创建router
const GuidancesRouter = new Router()
/**
 * @route POST api/Guidances/add
 * @description 咨询增加
 * @access      接口公开
 */
GuidancesRouter.post('/add',async(ctx) =>{
    const {userName,isAdmin,message} = ctx.request.body
    // 获取特定条件的咨询
    const data = await Guidances.findOne({userName})
    if(!data){
        // 正确执行时
        if(isAdmin !== undefined && message !== undefined){
            const newGuidances = new Guidances({
                userName,
                messageAry:[{isAdmin,message,Date:new Date()}]
            })
            // 存储到数据库
            newGuidances.save()
            // 向客户端返回数据
            ctx.status = 200
            ctx.body = {
                status:ctx.status,
                success:true,
                data:[{isAdmin,message,Date:new Date()}],
                msg:'消息发送成功'
            }
        }else{
            ctx.status = 200
            ctx.body = {
                status:ctx.status,
                success:true,
                msg:'还未发送过消息'
            }
        }
    }else{
        if(isAdmin == undefined && message == undefined){
            ctx.status = 200
            ctx.body = {
             status:ctx.status,
             success:true,
             data,
             msg:'咨询对话返回成功'
         }
        }else{
            // 对对话进行更新
        const updateMessage = {messageAry:[...data.messageAry,{isAdmin,message,Date:new Date()}]}
        // 对管理员数据库进行更新
        await Guidances.findByIdAndUpdate(data._id.toString(),updateMessage)
         // 向客户端返回数据
         ctx.status = 200
         ctx.body = {
             status:ctx.status,
             success:true,
             data:updateMessage,
             msg:'消息发送成功！'
         }
        }
    }
})
/**
 * @route GET api/Guidances/all
 * @description 获取所有的咨询
 * @access      接口公开
 */
GuidancesRouter.get('/all',async(ctx) =>{
    // 获取所有的咨询
    const data = await Guidances.find({})
    ctx.status = 200
         ctx.body = {
             status:ctx.status,
             success:true,
             data:data,
             msg:'所有咨询返回成功'
         }
})
module.exports = GuidancesRouter